package com.mark.common.utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

/**
 * @Description: 密码MD5加密工具类
 * @Author: Mark
 * @CreateDate: 2018/4/23.
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 *
 * 注：MD5加密具有不可逆性
 */
@Slf4j
public class MD5Util {

    private static final String[] HEX_DIGITS = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
    };

    private static String byteArrayToHexString(byte b[]) {
        StringBuilder resultStringBuilder = new StringBuilder();
        for (int i = 0; i < b.length; i++) {
            resultStringBuilder.append(byteToHexString(b[i]));
        }
        return resultStringBuilder.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return HEX_DIGITS[d1] + HEX_DIGITS[d2];
    }

    /**
     * 指定字符集加密
     *
     * @param origin ： 明文信息
     * @param charsetName ： 字符集
     * @return ： 密文
     */
    private static String md5Encode(String origin, String charsetName) {
        String resultString = "";
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetName == null || "".equals(charsetName)){
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            }else{
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetName)));
            }
        } catch (Exception exception) {
            log.error("MD5 MD5Encode Exception:{}",exception);
        }
        return resultString.toUpperCase();
    }

    /*****  对外暴露的接口    *************************************************************/

    /**
     * 密码加密 不推荐使用了
     * @param origin : 明文信息
     * @return ： 加密后信息
     */
    public static String md5EncodeUtf8(String origin) {
        try {
            origin = origin + PropertiesUtil.getProperty("password.salt", "");
            return md5Encode(origin, "utf-8");
        } catch (Exception e) {
            log.error("MD5 MD5EncodeUtf8:{}",e);
           throw  new RuntimeException(e);
        }
    }

    /**
     * 密码加密
     *
     * @param password ：明文密码
     * @param salt ：加密的盐值，唯一性
     * @return ：加密后的密码
     */
    public static String md5EncodeUtf8BySalt(String password ,String salt) {
        try {
            String origin = password + salt;
            return md5Encode(origin, "utf-8");
        } catch (Exception e) {
            log.error("MD5 MD5EncodeUtf8:{}",e);
            throw  new RuntimeException(e);
        }
    }

}
